﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Visitor;
using Taste;

namespace ASTClass
{
    class IdentAST : TerminalAST
    {
        public IdentAST() : base() { name = "Ident"; }
        public IdentAST(AST parent) : base(parent) { name = "Ident"; }

        public override AST Clone()
        {
            IdentAST ast = new IdentAST();
            ast.operators = operators;
            foreach (AST c in children)
                ast.children.Add(c.Clone());

            return ast;
        }

        public override void CodeGen(Taste.SymbolTable st, Taste.CodeFileGen cfg)
        {
            Var myvar = st.findLocalVar(this.Value);
            if (myvar != null)
            {
                //local
                cfg.AddCommand("subu", "$sp, $sp, 4");
                cfg.AddCommand("lw", "$t1, " + 4 * myvar.index + "($fp)");
                cfg.AddCommand("sw", "$t1, 0($sp)");
            }
            else
            {
                myvar = st.findGlobalVar(this.Value);
                if (myvar != null)
                {
                    //global
                    IdentAST tval = myvar.variable as IdentAST;
                    cfg.AddCommand("subu", "$sp, $sp, 4");
                    cfg.AddCommand("lw", "$t1, " + tval.Value + "($0)");
                    cfg.AddCommand("sw", "$t1, 0($sp)");
                }
                else
                {
                    //error
                    Console.WriteLine("Error, variable " + this.Value + " not found!");
                    throw new Exception();
                }
            }
        }

        #region Visitor pattern

        public override void Accept(IVisitor visitor)
        {
            visitor.Visit(this);
        }

        #endregion Visitor pattern
    }
}
